﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace SysFrame.BP
{
    public class EncryptDES
    {

        private static string _key = "MYSFEDES";

        public static string key
        {
            get { return _key; }
            set { _key = value; }
        }

        /// <summary>
        /// 加密算法
        /// </summary>
        /// <param name="encryptString"></param>
        /// <returns></returns>
        public static string strEncryptToDES(string encryptString)
        {

            try
            {

                byte[] rgbKey = Encoding.UTF8.GetBytes(key);

                //rgbIV与rgbKey可以不一样，这里只是为了简便，读者可以自行修改

                byte[] rgbIV = Encoding.UTF8.GetBytes(key);

                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);


                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);


                cStream.Write(inputByteArray, 0, inputByteArray.Length);

                cStream.FlushFinalBlock();

                return Convert.ToBase64String(mStream.ToArray()).ToUpper();

            }

            catch
            {

                return encryptString;

            }

        }

        /// <summary>
        /// 解密算法
        /// </summary>
        /// <param name="pToDecrypt">加密后</param>
        /// <returns></returns>
        public static string strEncryptByDES(string pToDecrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = UTF8Encoding.UTF8.GetBytes(key);
            des.IV = UTF8Encoding.UTF8.GetBytes(key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            return Encoding.UTF8.GetString(ms.ToArray());
        }



    }
}
